<?php

namespace App\Http\Controllers\BidQuote;

use App\Bid;
use App\Demand;
use App\Offer;
use App\Setting;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use URL;
use Validator;
use DB;

class BidQuoteController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     *
     */
    public function index()
    {
    }

    /**
     * @return mixed\
     * 已完成投标报价index页面，列表页
     */
    public function done()
    {
        $current_user = auth()->user();
        $current_supplier = $current_user->supplier;
        $supply_goods = json_decode($current_supplier->goods, true);
        $datetime = date('Y-m-d H:i:s');

		// test
        $bids = Bid::orderBy('created_at', 'desc')
            ->whereHas('basket', function($query) use($datetime) {
                return $query->where('state', 'bided')->where('bided_at', '<=', $datetime);
            });

        $bids = $bids->whereHas('demands', function($query) {
            return $query->select(DB::raw('CASE WHEN sum("quantity") > 0 THEN 1 ELSE 0 END'))->groupBy('bid_id');
        });

        $bids = $bids->where(function($query) use($supply_goods, $current_user) {
            return $query->where(function($query) use($supply_goods) {
                return $query->where('type', 'global')->whereIn('goods_id', $supply_goods);
            })->orWhere(function($query) use($current_user) {
                return $query->where('type', 'invite')->whereRaw('\'["' . $current_user->id . '"]\'::jsonb <@ "suppliers"');
            });
        });

        $bids = $bids->where('offer_stop', '<', $datetime);
        $bids = $bids->whereHas('offers', function($query) use($current_user) {
            return $query->where('user_id', $current_user->id);
        });

        $bids = $bids->paginate(10);
        // 分页HTML 的取得,  TODO 需要再深入了解下
        $pages = $bids->appends([])->render();

        // 更改CSS样式 为MUI
        $pages = str_replace("pagination","mui-pagination",$pages);
        $pages = str_replace("active","mui-active",$pages);
        $pages = str_replace("disabled","mui-disabled",$pages);
        $pages = str_replace("next","mui-next",$pages);

        return view('bid_quote.bid_quote_list')
            ->with('current_user', $current_user)
            ->with('bids', $bids)
            ->with('datetime', $datetime)
            ->with('pages', $pages);
    }

    /**
     * @return mixed
     */

    public function pending()
    {
        $current_user = auth()->user();
        $current_supplier = $current_user->supplier;
        $supply_goods = json_decode($current_supplier->goods, true);
        $datetime = date('Y-m-d H:i:s');

        $bids = Bid::orderBy('created_at', 'desc')
            ->whereHas('basket', function($query) use($datetime) {
                return $query->where('state', 'bided')->where('bided_at', '<=', $datetime);
            });

        $bids = $bids->whereHas('demands', function($query) {
            return $query->select(DB::raw('CASE WHEN sum("quantity") > 0 THEN 1 ELSE 0 END'))->groupBy('bid_id');
        });

        $bids = $bids->where(function($query) use($supply_goods, $current_user) {
            return $query->where(function($query) use($supply_goods) {
                return $query->where('type', 'global')->whereIn('goods_id', $supply_goods);
            })->orWhere(function($query) use($current_user) {
                return $query->where('type', 'invite')->whereRaw('\'["' . $current_user->id . '"]\'::jsonb <@ "suppliers"');
            });
        });

        $bids = $bids->where('offer_stop', '>=', $datetime)->where('offer_start', '<=', $datetime);

        $bids = $bids->paginate(10);
        $pages = $bids->appends([])->render();

        return view('bid_quote.bid_quote_list_pending')
            ->with('current_user', $current_user)
            ->with('bids', $bids)
            ->with('datetime', $datetime)
            ->with('pages', $pages);
    }

    /**
     * @param Bid $bid
     * @return mixed
     *
     * 查看已投标详细信息
     *
     */
    public function view(Bid $bid)
    {
        $datetime = date('Y-m-d H:i:s');
        $current_user = auth()->user();
        $demands = Demand::with(['company', 'company.delivery_modes', 'offer'])->whereBidId($bid->id)->where('quantity', '>', 0)->get();
        $goods = json_decode($bid->goods_static);

        return view('bid_quote.bid_quote_list_detail')
            ->with('demands', $demands)
            ->with('datetime', $datetime)
            ->with('goods', $goods)
            ->with('bid', $bid)
            ->with('current_user', $current_user);
    }
    
    /**
     * @param Bid $bid
     * @return mixed
     *
     * 查看待投标详细信息
     *
     */
    public function offer(Bid $bid)
    {
        $datetime = date('Y-m-d H:i:s');
        if ($datetime > $bid->offer_stop) {
            // 返回列表页
            return redirect(route('bidQuote.bqList'))->with('tip_message', ['content' => '已超过报价时间', 'state' => 'danger']);
        }
        if ($datetime < $bid->offer_start) {
            return redirect(route('bidQuote.bqList'))->with('tip_message', ['content' => '报价还未开始', 'state' => 'danger']);
        }
        $current_user = auth()->user();
        $demands = Demand::with(['company', 'company.delivery_modes', 'offer'])->whereBidId($bid->id)->where('quantity', '>', 0)->get();
        $goods = json_decode($bid->goods_static);

        return view('bid_quote.bid_quote_detail')
            ->with('demands', $demands)
            ->with('goods', $goods)
            ->with('bid', $bid)
            ->with('current_user', $current_user);
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     * 显示报价动作页
     */
    public function showDoWork(Demand $demand)
    {
        //
        $current_user = auth()->user();
        $goods = json_decode($demand->goods_static);

        // 新建报价时为空
        $offer = $demand->offer()->where('user_id', auth()->user()->id)->first();
        
        return view('bid_quote.bid_quote_detail_dowork')
            ->with('demand', $demand)
            ->with('goods', $goods)
            ->with('offer', $offer)
            ->with('current_user', $current_user);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     * 显示报价动作页
     */
    public function showDoRefuse(Demand $demand)
    {
        //
        $current_user = auth()->user();
        $offer = $demand->offer()->where('user_id', auth()->user()->id)->first();
        return view('bid_quote.bid_quote_detail_dorefuse')
            ->with('demand', $demand)
            ->with('offer', $offer);
    }



    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     * 新建报价数据
     */
    public function saveOffer(Request $request,Demand $demand)
    {
        $redirect_url = route('bidQuote.bqDetail.doWork', ['demand' => $demand->id]);
        $current_user = auth()->user();
        $time = time();
        $datetime = date('Y-m-d H:i:s', $time);

        $bid = $demand->bid;
        if ($bid->offer_stop < $datetime) {
            // 报价时间已过
            return redirect($redirect_url)->withErrors(['msg' => ['报价时间已过']])->withInput();
        }

        $demand_id = $demand->id;
        $offer_min_num_setting = Setting::where('name', 'offer_min_num')->first();
        if (empty($offer_min_num_setting)) {
            $offer_min_num = 3;
        } else {
            $offer_min_num = intval($offer_min_num_setting->data);
        }

        $assign_rule = json_decode($demand->assign_rule);
        $assign_rule_data = $assign_rule->rules;
        $assign_rule_data = json_decode($assign_rule_data, true);
        $assign = array_filter($assign_rule_data);
        arsort($assign);
        $assign_count = count($assign);
        $min_assign = min($assign);
        $quantity_floor = ($demand->quantity*$min_assign)/100;
        $form_data = $request->only(['quantity_caps', 'price', 'delivery_mode']);
        $rules = [
            'quantity_caps' => 'required|numeric|min:'.$quantity_floor,
            'price' => 'required|numeric|min:'.$demand->price_floor.'|max:'.$demand->price_caps
        ];
        $messages = [
            'quantity_caps.required' => '最高成交量不能为空',
            'quantity_caps.numeric' => '最高成交量只能为数字',
            'quantity_caps.min' => '最高成交量最小只能为:min',
            'price.required' => '报价不能为空',
            'price.numeric' => '报价只能为数字',
            'price.min' => '报价过低，请勿恶意报价',
            'price.max' => '报价过高'
        ];
        $validator = Validator::make($form_data, $rules, $messages);

        if ($validator->fails()) {
            // 返回信息
            return redirect($redirect_url)->withErrors($validator->errors())->withInput();
        }

        $offer = Offer::firstOrNew([
            'bid_id' => $bid->id,
            'demand_id' => $demand_id,
            'user_id' => $current_user->id
        ]);

        // 到货方式 将不插入
        //list($costs, $mode) = explode(',', $form_data['delivery_mode']);
        
        $offer->delivery_mode = "";
        $offer->delivery_costs = 0.00;
        $offer->price = $form_data['price'];
        $offer->quantity_floor = $quantity_floor;
        $offer->quantity_caps = $form_data['quantity_caps'];
        $offer->created_at = $datetime;
        $offer->updated_at = $datetime;

        $result = DB::transaction(function() use ($offer_min_num, $offer, $current_user, $bid, $demand, $assign, $assign_count, $datetime) {
            if (!$offer->save()) {
                return false;
            }

            $offers = Offer::orderBy(DB::raw('"price"+"delivery_costs"'))
                ->orderBy('updated_at', 'asc')
                ->where('price', '>', 0)
                ->where('demand_id', $demand->id)
                ->where('bid_id', $bid->id)
                //->take($assign_count)
                ->get();

            $offer_count = Offer::where('price', '>', 0)
                ->where('demand_id', $demand->id)
                ->where('bid_id', $bid->id)
                ->whereNull('reason')
                ->count();
            if ($offer_count >= $offer_min_num) {
                $demand->is_cancel = false;
                if (!$demand->save()) {
                    DB::rollBack();
                    return false;
                }
            }
            //DB::table('offers')->where('demand_id', $demand->id)->where('bid_id', $bid->id)->update(['quantity' => 0]);
            foreach ($offers as $k=>$offer_item) {
                if ($assign_count < $k+1) {
                    $assign_quantity = 0;
                } else {
                    $assign_quantity = ($demand->quantity * $assign[$k]) / 100;
                    $assign_quantity = sprintf('%.5f', $assign_quantity);
                    if ($offer_item->quantity_floor > $assign_quantity) {
                        $assign_quantity = 0;
                    }
                    if ($offer_item->quantity_caps < $assign_quantity) {
                        $assign_quantity = $offer_item->quantity_caps;
                    }
                }
                $update_data = ['quantity' => $assign_quantity];
                if (!DB::table('offers')->where('id', $offer_item->id)->where('updated_at', $offer_item->updated_at)->update($update_data)) {
                    DB::rollBack();
                    return false;
                }
            }
            return true;
        });
        if ($result) {
            // 成功后跳转
            $success_url =  route('bidQuote.bqList.pending', ['bid' => $bid->id]);
            return redirect($success_url)->with('tip_message', ['content' => '提交成功', 'state' => 'success']);
        } else {

            return redirect($redirect_url)->withErrors(['form' => ['服务器繁忙，请稍后再试']]);
        }

    }


    /**
     * @param Request $request
     * @param Demand $demand
     * @return mixed
     * 投标报价动作页，不参与
     */
    public function refuseOffer(Request $request,Demand $demand)
    {
        $current_user = auth()->user();
        $time = time();
        $datetime = date('Y-m-d H:i:s', $time);
        $bid = $demand->bid;
        $redirect_url = route('bidQuote.bqDetail', ['bid' => $bid->id]);
        if ($bid->offer_stop < $datetime){
            // 报价时间已过
            return redirect($redirect_url)->withErrors(['msg' => ['报价时间已过']])->withInput();
        }
        $demand_id = $demand->id;
        $reason = trim($request->get('reason', ''));
        $other = trim($request->get('other', ''));
        if ($reason == '其他' and !empty($other)) {
            $reason = $other;
        }

        $offer = Offer::firstOrNew([
            'bid_id' => $bid->id,
            'demand_id' => $demand_id,
            'user_id' => $current_user->id
        ]);
        if ($offer->exists) {
            //返回消息
            //已经报价或提交了不参与操作
            return redirect($redirect_url)->withErrors(['msg' => ['已经报价或提交了不参与操作']])->withInput();
        }
        $offer->delivery_mode = '无';
        $offer->delivery_costs = 0;
        $offer->price = 0;
        $offer->quantity_floor = 0;
        $offer->quantity_caps = 0;
        $offer->created_at = $datetime;
        $offer->updated_at = $datetime;
        $offer->reason = $reason;
        try {
            if ($offer->save()) {
                return redirect($redirect_url)->with('tip_message', ['content' => '提交成功', 'state' => 'success']);
            } else {
                return redirect($redirect_url)->withErrors(['form' => ['服务器繁忙，请稍后再试']]);
            }
        } catch (\Exception $e) {
            return redirect($redirect_url)->withErrors(['form' => ['服务器繁忙，请稍后再试']]);
        }

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //


    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
